#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;


const int gdefaultfd = -1;


// 最开始的时候,我们的服务器,只有一个文件描述符
class EpollServer
{
    static const int revs_num = 64;
public:
    EpollServer(int port) : _port(port),
                             _listen_socket(std::make_unique<TcpSocket>()),
                             _isrunning(false),
                             _epfd(gdefaultfd)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocket(_port);
        //1.创建epoll模型
        _epfd = epoll_create(256);
        if(_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll create error";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::DEBUG) << "epoll_create success" << _epfd;

        //2.将listensocket添加到epoll模型中
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_socket->Fd();
        int n = epoll_ctl(_epfd,EPOLL_CTL_ADD,_listen_socket->Fd(),&ev);
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll ctl error";
            exit(EPOLL_CTL_ERR);
        }
    }
    void Loop()
    {
        int timeout = 10000;
        _isrunning = true;
        while (_isrunning)
        {
            int n = epoll_wait(_epfd,_revs,revs_num,timeout);
            //完成通知上层的任务
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                // rfds: 内核告诉用户,你关心的rfds中的fd,有哪些已经就绪了
                Dispatcher(n);
                break;
            }
        }
        _isrunning = false;
    }
    void Accepter()
    {
        InetAddr client;
        // listensockfd就绪了! 再获取新连接
        int newfd = _listen_socket->Accepter(&client);
        // 这里进行accept不会被阻塞了,因为我们是被select叫来的,只执行拷贝
        if (newfd < 0)
        {
            return;
        }
        else
        {
            std::cout << "获取了一个新的连接: " << newfd << " client info: " << client.Addr() << std::endl;
            //我们要将其添加到对应的epoll,让epoll帮我们进行监管
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = newfd;
            int n = epoll_ctl(_epfd,EPOLL_CTL_ADD,newfd,&ev);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll ctl error";
                close(newfd);
            }
            LOG(LogLevel::DEBUG) << "epoll ctl success: " << newfd;
        }
    }
    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = recv(fd,buffer,sizeof(buffer)-1,0);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " <<buffer << std::endl;
            std::string message = "echo# ";
            message += buffer;
            send(fd,message.c_str(),message.size(),0);
        }
        else if(n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << fd;
            
            //把对应的文件描述符从epoll中进行移除
            //在移除的时候,我们应该将其先进行移除,再关闭
            int m = epoll_ctl(_epfd,EPOLL_CTL_DEL,fd,nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll ctl success: " << fd;
            close(fd);
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " << fd;
            
            //把对应的文件描述符从epoll中进行移除
            int m = epoll_ctl(_epfd,EPOLL_CTL_DEL,fd,nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll ctl success: " << fd;
            close(fd);
        }
    }

    void Dispatcher(int rnum)
    {
        for (int i = 0; i < rnum; i++)
        {
            int events = _revs[i].events;
            int fd = _revs[i].data.fd;
            if(fd == _listen_socket->Fd())
            {
                if(events & EPOLLIN)
                {
                    //listen sock fd
                    Accepter();
                }
            }
            else
            {
                if(events & EPOLLIN)
                {
                    //读事件就绪
                    Recver(fd);
                }
                // else if(events & EPOLLOUT)
                // {
                //     //写事件就绪
                // }
            }
        }
    }
    ~EpollServer()
    {
        _listen_socket->Close();
        if(_epfd >= 0)
        {
            close(_epfd);
        }
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    int _epfd;
    struct epoll_event _revs[revs_num];
};
